package com.tg.app.activity.device.add;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.demo.view.LoadingDialog;
import com.tange.module.add.connect.DeviceApConnect;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tg.app.R;
import com.tg.app.helper.ActivityHelper;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;

/**
 * 加入网络引导：
 *
 * 为设备选择网络 这个页面，点击"下一步"的时候，打开 此页面 startForResult
 *
 * 这样的好处就是不用改动之前的流程，改动比较小。
 *
 */
public  class WiFiAccessGuideActivity extends ApBaseActivity {

    public static final int REQUEST_CODE = 9999;

    private static final String TAG =  "WiFiAccessGuideActivityTAG";

    private static final String PARAM_AP_SSID = "PARAM_AP_SSID";

    private String deviceWifiName = "";

    private LoadingDialog scanningDialog;

    private LoadingDialog loadingDialog;

    private View editLayout;

    private EditText editText;

    private View errorLayout;

    private CheckBox pwdCheckBox;

    private DeviceApConnect deviceApConnect;

    private String mUUID;
    public static void launch(Activity activity, String deviceWifiName, String uuid) {
        Intent intent = new Intent(activity, WiFiAccessGuideActivity.class);
        if (StringUtils.isEmpty(uuid) && !StringUtils.isEmpty(deviceWifiName)){
            uuid =  deviceWifiName.replaceAll(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine(),"");
        }
        intent.putExtra(PARAM_AP_SSID, deviceWifiName);
        intent.putExtra(ApSetWifiActivity.EXT_UUID, uuid);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fragment_wifi_access_guide);
        hideActionBar();


        mUUID = getIntent().getStringExtra(ApSetWifiActivity.EXT_UUID);
        deviceWifiName = getIntent().getStringExtra(PARAM_AP_SSID);

        deviceApConnect = DeviceApConnect.create(this, deviceWifiName, null, new DeviceApConnect.Callback() {
            @Override
            public void onConnected() {
                TGLog.i(TAG, "[DeviceApConnect] onConnected: ");
                launchNextStep();
            }

            @Override
            public void onScanned(boolean isApPasswordRequired) {
                TGLog.i(TAG, "[DeviceApConnect] onScanned: " + isApPasswordRequired);
                if (scanningDialog.isShowing()) {
                    scanningDialog.dismiss();
                }
                if (isApPasswordRequired) {
                    editLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(int errorCode) {
                TGLog.i(TAG, "[DeviceApConnect] onError: " + errorCode);
                if (scanningDialog.isShowing()) {
                    scanningDialog.dismiss();
                }
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                showErrorLayout();
            }
        });

        initView();

        TGLog.i(TAG, "onCreate: deviceWifiName = " + deviceWifiName);
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        TGLog.i(TAG, "onResume");

        deviceApConnect.checkApConnected();
    }

    @Override
    protected void wifiListChanged() {
        TGLog.i(TAG, "wifiListChanged: ");
    }

    @Override
    protected void wifiConnected() {

    }

    @Override
    public void onBackPressed() {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            TGLog.i(TAG, "KEYCODE_BACK");
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void connectWiFi(){
        TGLog.i(TAG, "connectWiFi ...");
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        deviceApConnect.setApPassword(editText.getText().toString());
        deviceApConnect.start(true);
    }

    private void showErrorLayout() {
        TGLog.i(TAG, "connect timeout, show error tips");
        if (WiFiAccessGuideActivity.this.isFinishing() || WiFiAccessGuideActivity.this.isDestroyed()) {
            return;
        }
        errorLayout.post(() -> errorLayout.setVisibility(View.VISIBLE));
    }

    @Override
    protected void wifiUnavailable() {
        TGLog.i(TAG, "wifiUnavailable: ");
    }

    private void launchNextStep() {
        TGLog.i(TAG, "launchNextStep");
        loadingDialog.dismiss();
        final Handler h = new Handler(Looper.getMainLooper());
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                setResult(RESULT_OK);
                finish();
            }
        }, 100);

    }

    @Override
    protected void onDestroy() {
        TGLog.i(TAG, "onDestroy");
        super.onDestroy();
        deviceApConnect.destroy();
    }

    @Override
    protected void initView() {

        pwdCheckBox = findViewById(R.id.checkBox);

        editLayout = findViewById(R.id.layout_edit);

        editText = findViewById(R.id.edt_password);

        pwdCheckBox.setOnClickListener(v -> {
            if (pwdCheckBox.isChecked()) {
                editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            if (editText.getText().toString().trim().length() > 0) {
                editText.setSelection(editText.getText().toString().trim().length());
            }
        });

        pwdCheckBox.setChecked(true);
        editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

        findViewById(R.id.back_toolbar).setOnClickListener(v -> {
            setResult(RESULT_CANCELED);
            finish();
        });

        TextView tv = findViewById(R.id.tv_device_ap_add_sub_title);
        tv.setText(String.format(getResources().getString(R.string.please_allow_join_wifi), deviceWifiName));

        findViewById(R.id.join).setOnClickListener(v -> connectWiFi());

        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCancelable(false);
        loadingDialog.setMsg(R.string.scan_qrcode_connecting);

        scanningDialog = new LoadingDialog(this);
        scanningDialog.setCancelable(false);
        scanningDialog.setMsg(R.string.searching);

        errorLayout = findViewById(R.id.join_net_error_layout);

        findViewById(R.id.btn_1).setOnClickListener(v -> tryOtherAddType());


        TextView btn2 = findViewById(R.id.btn_2);
        btn2.setOnClickListener(v -> deviceApConnect.connectByManual());
        btn2.setText(String.format(getResources().getString(R.string.join_wifi_fail_tips_6), deviceWifiName));

        // 开始扫描WiFi
        scanningDialog.show();

        deviceApConnect.start(false);
    }

    private void tryOtherAddType() {
        ActivityHelper.gotoAddDeviceHomePage(this);
        setResult(RESULT_FIRST_USER);
        finish();
    }
}
